import Input from '@/components/Input';
import NavBar from '@/components/NavBar';
import Textarea from '@/components/TextArea';
import {
  editProFileAction,
  getUserProfileAction,
  updatePhotoAction,
} from '@/store/action/user';
import { useAppSelector } from '@/store/reducer';
import { ProFileType } from '@/store/reducer/user';
import { removeToken } from '@/utils/storage';
import { DatePicker, Dialog, List, Popup, Toast } from 'antd-mobile';
import Dayjs from 'dayjs';
import { useEffect, useRef, useState } from 'react';
import { useDispatch } from 'react-redux';
import { useHistory } from 'react-router-dom';
import styles from './index.module.scss';

export default function ProfileEdit() {
  const history = useHistory();
  const dispatch = useDispatch();

  // 挂载时,发送请求
  useEffect(() => {
    dispatch(getUserProfileAction());
  }, [dispatch]);

  // 取数据
  const { profile } = useAppSelector((state) => state.user);

  // 弹出层状态
  const [visible, setVisible] = useState(false); //底部弹出层
  const [rightVisible, setRightVisible] = useState(false); //右侧弹出层
  // 昵称input
  const [name, setName] = useState('');
  // 简介intro
  const [intro, setIntro] = useState('');
  // 声明生日显示的状态
  const [birthVisible, setBirthVisible] = useState(false);
  // 监听profile发生改变时修改name
  useEffect(() => {
    setName(profile.name);
  }, [profile.name]);
  useEffect(() => {
    setIntro(profile.intro || '');
  }, [profile.intro]);

  //修复未提交时,关闭右侧弹出层,name状态没有还原
  const handleBack = () => {
    setRightVisible(false);
    editType === 'name' && setName(profile.name);
    editType === 'intro' && setIntro(profile.intro || '');
  };
  // 新增回车提交修改昵称
  const handleKeyDown = (
    e: React.KeyboardEvent<HTMLInputElement | HTMLTextAreaElement>
  ) => {
    if (e.key === 'Enter') {
      editType === 'name' && handleUpdateProFile({ name });
      editType === 'intro' && handleUpdateProFile({ intro });
    }
  };

  type EditType = 'photo' | 'gender' | 'name' | 'intro';
  // 定义复用模态框的变量
  const [editType, setEditType] = useState('' as EditType);
  // const [editType, setEditType] = useState<EditType>('photo');

  // 触发上传图片
  const updateRef = useRef<HTMLInputElement>(null);
  const handleUpdateClick = () => {
    updateRef.current?.click();
  };

  //点击上传图片触发
  const handleFlieChannge = async (e: React.ChangeEvent<HTMLInputElement>) => {
    setVisible(false);
    //用fromDate修改数据
    // Content-Type:multipart/form-data
    let fromDate = new FormData();
    if (e.target.files) {
      // console.log(e.target.files[0]);
      fromDate.append('photo', e.target.files[0]);
    }
    await dispatch(updatePhotoAction(fromDate));
    Toast.show({ content: '修改成功' });
  };

  // 编辑用户个人资料
  const handleUpdateProFile = async (data: Partial<ProFileType>) => {
    await dispatch(editProFileAction(data));
    Toast.show({ content: '修改成功' });
    setVisible(false);
    setRightVisible(false);
  };

  // 打开底部弹出层
  const handleShowEdit = (editType: EditType) => {
    setEditType(editType);
    if (editType === 'name' || editType === 'intro') {
      setRightVisible(true);
    }
    if (editType === 'photo' || editType === 'gender') {
      setVisible(true);
    }
  };
  // // 打开右侧弹出层
  // const handleShowRightEdit = (editType: EditType) => {
  //   setEditType(editType);
  //   setRightVisible(true);
  // };

  // 退出登录
  const handleLogOut = () => {
    // 二次确认
    Dialog.confirm({
      title: '温馨提示',
      content: '亲，您确定要退出吗？',
      onConfirm: () => {
        // 清除token
        removeToken();
        // 跳转路由
        history.push('/login');
        // 提示用户
        Toast.show({ content: '退出登录成功' });
      },
    });
  };

  return (
    <div className={styles.root}>
      <div className="content">
        {/* 顶部导航栏 */}
        <NavBar>个人资料</NavBar>

        <div className="wrapper">
          {/* 列表一：显示头像、昵称、简介 */}
          <List className="profile-list">
            <List.Item
              arrow
              extra={<img className="avatar" src={profile.photo} alt="" />}
              onClick={() => handleShowEdit('photo')}
            >
              头像
            </List.Item>

            <List.Item
              arrow
              extra={profile.name}
              onClick={() => handleShowEdit('name')}
            >
              昵称
            </List.Item>

            <List.Item
              arrow
              extra={<span className="intro">{profile.intro || '未填写'}</span>}
              onClick={() => handleShowEdit('intro')}
            >
              简介
            </List.Item>

            <List.Item
              arrow
              extra={profile.gender === 0 ? '男' : '女'}
              onClick={() => handleShowEdit('gender')}
            >
              性别
            </List.Item>
            <List.Item
              arrow
              extra={profile.birthday}
              onClick={() => setBirthVisible(true)}
            >
              生日
            </List.Item>
          </List>

          {/* 文件选择框，用于头像图片的上传 */}
          <input
            className="avatar-upload"
            type="file"
            ref={updateRef}
            onChange={(e) => handleFlieChannge(e)}
          />
        </div>

        {/* 底部栏：退出登录按钮 */}
        <div className="logout">
          <button className="btn" onClick={handleLogOut}>
            退出登录
          </button>
        </div>
      </div>
      {/* 底部弹出层 */}
      <Popup
        visible={visible}
        position="bottom"
        bodyClassName="popup-bottom-list"
        onMaskClick={() => setVisible(false)}
      >
        {editType === 'photo' && (
          <>
            <div className="list-item" onClick={handleUpdateClick}>
              拍照
            </div>
            <div className="list-item" onClick={handleUpdateClick}>
              本地选择
            </div>
          </>
        )}
        {editType === 'gender' && (
          <>
            <div
              className="list-item"
              onClick={() => handleUpdateProFile({ gender: 0 })}
            >
              男
            </div>
            <div
              className="list-item"
              onClick={() => handleUpdateProFile({ gender: 1 })}
            >
              女
            </div>
          </>
        )}

        <div className="list-item" onClick={() => setVisible(false)}>
          取消
        </div>
      </Popup>
      {/* 右侧弹出层 */}
      <Popup
        visible={rightVisible}
        position="right"
        bodyClassName="popup-right"
        destroyOnClose
      >
        {editType === 'name' && (
          <>
            <NavBar
              onBack={() => handleBack()}
              right={
                <span
                  className="submit-btn"
                  onClick={() => handleUpdateProFile({ name })}
                >
                  提交
                </span>
              }
            >
              编辑昵称
            </NavBar>

            <div className="edit-content">
              <Input
                className="edit-input"
                placeholder="请输入昵称"
                autoFocus
                value={name}
                onChange={(e) => setName(e.target.value)}
                onKeyDown={(e) => handleKeyDown(e)}
              />
            </div>
          </>
        )}
        {editType === 'intro' && (
          <>
            <NavBar
              onBack={handleBack}
              right={
                <span
                  className="submit-btn"
                  onClick={() => handleUpdateProFile({ intro })}
                >
                  提交
                </span>
              }
            >
              编辑简介
            </NavBar>

            <div className="edit-content">
              <Textarea
                value={intro}
                onChange={(e) => setIntro(e.target.value)}
                placeholder="请输入内容"
                onKeyDown={(e) => handleKeyDown(e)}
              ></Textarea>
            </div>
          </>
        )}
      </Popup>

      {/* 生日弹框 */}
      <DatePicker
        title="选择生日"
        // 绑定显示隐藏
        visible={birthVisible}
        // 取消和确认都会触发
        onClose={() => {
          setBirthVisible(false);
        }}
        // 设置默认值
        defaultValue={new Date()}
        value={new Date(profile.birthday)}
        // 设置最大最小值
        max={new Date()}
        min={new Date('1970-01-01')}
        // 确认
        onConfirm={(val) => {
          //使用dayjs格式化日期
          handleUpdateProFile({ birthday: Dayjs(val).format('YYYY-MM-DD') });
        }}
      />
    </div>
  );
}
